﻿using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace NSuggest.Jsonp.Core
{
    /// <summary>
    /// A class that provides functionality to clone types that use the DataContract/DataMember attributes.
    /// </summary>
    public static class ObjectCloneExtension
    {
        /// <summary>
        /// Return a clone of the given source
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The object to clone.</param>
        /// <returns></returns>
        public static T Clone<T>(this T source)
        {
            var clsType = typeof (T);

            if (!Attribute.IsDefined(clsType, typeof(DataContractAttribute)))
            {
                throw new ArgumentException("The type must be have the DataContract attribute.", source.GetType().Name);
            }

            // Don't serialize a null object, simply return the default for that object
            if (ReferenceEquals(source, null))
            {
                return default(T);
            }

            var serializer = new DataContractSerializer(clsType);
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, source);
                var pickle = Encoding.Default.GetString(ms.ToArray());
                Console.WriteLine(pickle);
                using (var stream = new MemoryStream(Encoding.Default.GetBytes(pickle.ToArray())))
                {
                    var clone = (T)serializer.ReadObject(stream);
                    return clone;
                }
            }
        }
    }
}
